//
//  AsyncPostURLConnection.m
//  网络请求
//
//  Created by zhang on 15/8/7.
//  Copyright (c) 2015年 张益. All rights reserved.
//

#import "AsyncPostURLConnection.h"


@interface AsyncPostURLConnection ()<NSURLConnectionDataDelegate, NSURLConnectionDelegate>

@end

@implementation AsyncPostURLConnection


- (instancetype) init{
    self = [super init];
    if (self) {
        self.receiveData = [NSMutableData data];
    }
    return self;
}


+ (instancetype)asyncPostConncetWith:(NSString *)URLStr parmaters:(NSDictionary *)parmaters message:(void(^)(NSData *data))block{
    AsyncPostURLConnection *async = [[AsyncPostURLConnection alloc] init];
    [async stratConnect:URLStr parmaters:parmaters];
    async.dataBlock = block;
    return async;
    
}


- (void)stratConnect:(NSString *)urlStr  parmaters:(NSDictionary *)parmaters{
    
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    
    // 添加post参数
    NSString *par = @"";
    for (NSString *key in [parmaters allKeys]) {
        if (par.length == 0) {
            par = [NSString stringWithFormat:@"%@=%@", key, [parmaters objectForKey:key]];
        }
        par = [NSString stringWithFormat:@"%@&%@=%@", par, key, [parmaters objectForKey:key]];
    }
    NSData *parData = [par dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:parData];
    
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.receiveData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    self.dataBlock(self.receiveData);
}



@end
